const { src, dest, watch, parallel, series } = require("gulp")
const webserver = require("gulp-webserver")
const sass = require("gulp-sass")
const concat = require("gulp-concat")
const webpackSteam = require("webpack-stream")
const proxy = require("http-proxy-middleware")


function copyFonts() {//复制字体文件
    return src("./src/fonts/*.*")
        .pipe(dest("./dev/fonts/"))
}

function copyHtml() {//复制html文件
    return src("./src/html/*.html")
        .pipe(dest("./dev/html/"))
}

function copyIndexHtml() {//复制主页html文件
    return src("./src/index.html")
        .pipe(dest("./dev/"))
}

function copyImages() {//复制图片文件
    return src("./src/images/*.*")
        .pipe(dest("./dev/images/"))
}

function copyLibs() {//复制静态文件
    return src("./src/libs/*.*")
        .pipe(dest("./dev/libs/"))
}

function compileCss() {//编译整合css文件
    return src("./src/style/*.scss")
        .pipe(sass().on('error', sass.logError))
        .pipe(concat("app.min.css"))
        .pipe(dest("./dev/style/"))
}

function compileJs() {//打包js依赖文件
    return webpackSteam({
        mode: "development",
        entry: "./src/javascript/app.js",
        devtool: "source-map",
        output: {
            filename: "app.min.js"
        },
        module: {
            rules: [
                {
                    test: /\.js$/,
                    exclude: /node_modules/,
                    use: {
                        loader: "babel-loader",
                        options: {
                            presets: ['@babel/preset-env'],
                            plugins: ['@babel/plugin-transform-runtime']
                        }
                    }
                },
                {
                    test: /\.html$/,
                    loader: "string-loader"
                }
            ]
        }
    })
        .pipe(dest("./dev/javascript/"))
}

function watchFile() {
    watch("./src/fonts/*.*", copyFonts)//监听字体文件变动
    watch("./src/html/*.html", copyHtml)//监听html文件变动
    watch("./src/index.html", copyIndexHtml)//监听主页html变动
    watch("./src/images/*.*", copyImages)//监听图片变动
    watch("./src/libs/*.*", copyLibs)//监听静态文件变动
    watch("./src/style/*.scss", compileCss)//监听css样式文件变动
    watch("./src/javascript/**/*.*", compileJs)//监听javascript文件夹内的文件变动
}

function server() {
    return src("./dev")
        .pipe(webserver({
            livereload: true,
            open: true,
            port: 8080,
            middleware: [   //添加中间件
                proxy('/api/',{       //代理服务器中间件  路由匹配成功执行下面操作
                    target:"https://m.lagou.com",      //代理服务器目标服务器
                    changeOrigin:true,      //执行跨域
                    pathRewrite:{           //改写路由地址 匹配内容替换
                        "^/api/":""
                    }

                })
            ]
        }))
}


exports.default = series(parallel(copyFonts, copyIndexHtml, copyHtml, copyImages, copyLibs, compileCss, compileJs), server, watchFile)